import React, { useState } from 'react'
import axios from 'axios'
import { useNavigate } from 'react-router-dom'
export default function Zhuce() {
  const [phone, setphone] = useState('')
  const [yanZhengma, setYanZhengma] = useState('')
  const [errorMessage, setErrorMessage] = useState('')
  const [IsCode, setIsCode] = useState(false)
  const [password, setpassword] = useState('')
  const navigate = useNavigate()
  const reg = /^1[3-9]\d{9}$/
  const sendCode = () => {
    if (!phone) {
      setErrorMessage('手机号不能为空')
      return;
    }
    if(!reg.test(phone)){
      setErrorMessage('请输入正确的手机号')
      return;
    }
    axios.post('http://127.0.0.1:3001/sendYzm', { phone: phone }).then(res => {
      if (res.status == 200) {
        if (res.data.code === 200) {
          setErrorMessage('')
          setIsCode(true)
          alert('验证码已发送')
        } else {
          alert('验证码发送失败')
          setErrorMessage(res.data.message)
        }
      } else {
        alert(`请求失败，状态码: ${res.status}`);
        setErrorMessage('请求失败，请稍后再试');
      }

    })
  }
  const register = () => {
    axios.post('http://localhost:3001/register', { phone, code: yanZhengma, password }).then(res => {
      if (res.status == 200) {
        if (res.data.code === 200) {
          setErrorMessage('')
          alert('注册成功')
          navigate('/login')
        } else {
          alert(res.data.msg);
          setErrorMessage(res.data.msg);
        }
      } else {
        alert(`请求失败，状态码: ${res.status}`);
        setErrorMessage('请求失败，请稍后再试');
      }
    })
  }


  return (
    <div>
      <div className='zhu'>
        <h2>注册</h2>
        <input type="text" value={phone} onChange={(event) => {
          setphone(event.target.value)
        }} placeholder='请输入手机号' className='input'/>

        <input type="text" placeholder='请输入验证码' value={yanZhengma} onChange={(event) => {
          setYanZhengma(event.target.value)
        }} className='input'/>
        <button onClick={sendCode} style={{ position: 'absolute', top: '345px', left: '260px', border: 'none', color: 'blue',backgroundColor:'#fff' }} >发送验证码</button>
       
        {IsCode && (
          <div>
            <input
              type="password"
              placeholder="请输入密码"
              value={password}
              className='input'
              onChange={(event) => {
                setpassword(event.target.value);
              }}
              
            />
            
          </div>
        )}
        {errorMessage && <p style={{ color: 'red',textAlign:'left',marginLeft:'20px' }}>{errorMessage}</p>}
        
        <button className='button' onClick={register}>注册</button>
         <p style={{ marginLeft: '150px' }}>已有账号？<span style={{ color: '#14cfb4', cursor: 'pointer' }} onClick={() => navigate('/login')}>立即登录</span></p>
      </div>
    </div>
  )
}
